package com.yuntsg.nnsfcp.service.front.impl;

import com.yuntsg.nnsfcp.service.front.SendEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;

/**
 * 发送邮件实现类
 *
 * @author ：ljx
 * @date ：Created in 2019/11/12
 */
@Slf4j
@Service
public class SendEmailServiceImpl implements SendEmailService {

    @Resource
    private JavaMailSenderImpl mailSender;


    /**
     * 发送普通文本样式的邮件
     *
     * @param toMails     收件人
     * @param mailTitle   邮件标题
     * @param mailContent 邮件内容
     */
    @Override
    public boolean sendTextEmail(String[] toMails, String mailTitle, String mailContent) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            //收件人
            simpleMailMessage.setTo(toMails);
            //寄件人
            simpleMailMessage.setFrom("gechengrui09@163.com");
            //邮件标题
            simpleMailMessage.setSubject(mailTitle);
            //邮件内容
            simpleMailMessage.setText(mailContent);
            // 发送邮件
            mailSender.send(simpleMailMessage);

            log.info("Text邮件发送成功");
            log.info("收件人: " + Arrays.toString(toMails));
            log.info("邮件标题: " + mailTitle);
            return true;
        } catch (MailException e) {
            log.error("邮件发送失败");
//            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送html文本形式的邮件, html自动解析为样式
     *
     * @param toMails         收件人
     * @param mailTitle       邮件标题
     * @param mailHtmlContent html内容<html></html>
     */
    @Override
    public boolean sendHtmlEmail(String[] toMails, String mailTitle, String mailHtmlContent) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            //收件人
            mimeMessageHelper.setTo(toMails);
            //寄件人
            mimeMessageHelper.setFrom("ljx950429@163.com");
            //邮件标题
            mimeMessageHelper.setSubject(mailTitle);
            //邮件内容, 且标注启用html
            mimeMessageHelper.setText(mailHtmlContent, true);
            // 发送邮件
            mailSender.send(mimeMessage);

            log.info("HTML邮件发送成功");
            log.info("收件人: " + Arrays.toString(toMails));
            log.info("邮件标题: " + mailTitle);
            return true;
        } catch (Exception e) {
            log.error("邮件发送失败..");
            e.printStackTrace();
        }
        return false;
    }
}
